<template>
  <div class="class-form-page">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><EditPen /></el-icon>
            {{ isEdit ? '编辑班级信息' : '新增班级' }}
          </span>
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px; margin: 20px auto"
      >
        <el-form-item label="班级名称" prop="className">
          <el-input
            v-model="form.className"
            placeholder="请输入班级名称（如：一年级1班、2024级计算机1班）"
            maxlength="50"
            show-word-limit
          >
            <template #prefix>
              <el-icon><School /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            班级名称需唯一，建议包含年级信息
          </div>
        </el-form-item>

        <el-form-item label="年级" prop="grade">
          <el-autocomplete
            v-model="form.grade"
            :fetch-suggestions="queryGrades"
            placeholder="请输入或选择年级（如：一年级、2024级）"
            style="width: 100%"
          >
            <template #prefix>
              <el-icon><Calendar /></el-icon>
            </template>
          </el-autocomplete>
          <div class="form-tip">
            可以直接输入新年级，或从已有年级中选择
          </div>
        </el-form-item>

        <el-form-item label="班主任" prop="headTeacher">
          <el-input
            v-model="form.headTeacher"
            placeholder="请输入班主任姓名（选填）"
            maxlength="20"
            show-word-limit
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="备注" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
            size="large"
            style="width: 120px"
          >
            {{ isEdit ? '保存修改' : '立即创建' }}
          </el-button>
          <el-button @click="handleReset" size="large" style="width: 120px">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getClass, createClass, updateClass, getGrades } from '@/api/class'

const router = useRouter()
const route = useRoute()
const formRef = ref()

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive({
  className: '',
  grade: '',
  headTeacher: '',
  description: ''
})

// 年级列表（用于自动完成）
const gradeList = ref([])

// 提交状态
const submitting = ref(false)

// 表单验证规则
const rules = {
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 50, message: '班级名称长度在2-50个字符', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' },
    { max: 20, message: '年级长度不能超过20个字符', trigger: 'blur' }
  ],
  headTeacher: [
    { max: 20, message: '班主任姓名长度不能超过20个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '备注长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 加载班级详情（编辑模式）
const loadClass = async () => {
  try {
    const res = await getClass(route.params.id)
    Object.assign(form, {
      className: res.data.data.className,
      grade: res.data.data.grade,
      headTeacher: res.data.data.headTeacher || '',
      description: res.data.data.description || ''
    })
  } catch (error) {
    ElMessage.error('加载班级信息失败')
    router.back()
  }
}

// 加载年级列表
const loadGrades = async () => {
  try {
    const res = await getGrades()
    gradeList.value = res.data.data.map(grade => ({ value: grade }))
  } catch (error) {
    console.error('加载年级列表失败:', error)
  }
}

// 年级自动完成查询
const queryGrades = (queryString, cb) => {
  const results = queryString
    ? gradeList.value.filter(item => 
        item.value.toLowerCase().includes(queryString.toLowerCase())
      )
    : gradeList.value
  cb(results)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    submitting.value = true

    if (isEdit.value) {
      // 更新班级
      await updateClass(route.params.id, form)
      ElMessage.success('保存成功')
    } else {
      // 创建班级
      await createClass(form)
      ElMessage.success('创建成功')
    }

    router.push('/classes')
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请检查表单填写是否正确')
    } else {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (isEdit.value) {
    loadClass()
  } else {
    formRef.value?.resetFields()
  }
}

// 返回
const handleBack = () => {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    loadClass()
  }
  loadGrades()
})
</script>

<style scoped>
.class-form-page {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
